85f2b1a5770ac81be2549a1084cb7198810ded25
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 * @ingroup Upload
6 *
7 * Form for handling uploads and special page.
8 *
9 */
10
11 class SpecialUpload extends SpecialPage {
12 /**
13 * Constructor : initialise object
14 * Get data POSTed through the form and assign them to the object
15 * @param WebRequest $request Data posted.
16 */
17 public function __construct( $request = null ) {
18 global $wgRequest;
19
20 parent::__construct( 'Upload', 'upload' );
21
22 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
23 }
24
25 /** Misc variables **/
26 protected $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
27 protected $mSourceType;
28 protected $mUpload;
29 protected $mLocalFile;
30 protected $mUploadClicked;
31
32 /** User input variables from the "description" section **/
33 public $mDesiredDestName; // The requested target file name
34 protected $mComment;
35 protected $mLicense;
36
37 /** User input variables from the root section **/
38 protected $mIgnoreWarning;
39 protected $mWatchThis;
40 protected $mCopyrightStatus;
41 protected $mCopyrightSource;
42
43 /** Hidden variables **/
44 protected $mDestWarningAck;
45 protected $mForReUpload; // The user followed an "overwrite this file" link
46 protected $mCancelUpload; // The user clicked "Cancel and return to upload form" button
47 protected $mTokenOk;
48 protected $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
49
50 /** Text injection points for hooks not using HTMLForm **/
51 public $uploadFormTextTop;
52 public $uploadFormTextAfterSummary;
53
54
55 /**
56 * Initialize instance variables from request and create an Upload handler
57 *
58 * @param WebRequest $request The request to extract variables from
59 */
60 protected function loadRequest( $request ) {
61 global $wgUser;
62
63 $this->mRequest = $request;
64 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
65 $this->mUpload = UploadBase::createFromRequest( $request );
66 $this->mUploadClicked = $request->wasPosted()
67 && ( $request->getCheck( 'wpUpload' )
68 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
69
70 // Guess the desired name from the filename if not provided
71 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
72 if( !$this->mDesiredDestName )
73 $this->mDesiredDestName = $request->getText( 'wpUploadFile' );
74 $this->mComment = $request->getText( 'wpUploadDescription' );
75 $this->mLicense = $request->getText( 'wpLicense' );
76
77
78 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
79 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
80 || $request->getCheck( 'wpUploadIgnoreWarning' );
81 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
82 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
83 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
84
85
86 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
87 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
88 || $request->getCheck( 'wpReUpload' ); // b/w compat
89
90 // If it was posted check for the token (no remote POST'ing with user credentials)
91 $token = $request->getVal( 'wpEditToken' );
92 if( $this->mSourceType == 'file' && $token == null ) {
93 // Skip token check for file uploads as that can't be faked via JS...
94 // Some client-side tools don't expect to need to send wpEditToken
95 // with their submissions, as that's new in 1.16.
96 $this->mTokenOk = true;
97 } else {
98 $this->mTokenOk = $wgUser->matchEditToken( $token );
99 }
100
101 $this->uploadFormTextTop = '';
102 $this->uploadFormTextAfterSummary = '';
103 }
104
105 /**
106 * This page can be shown if uploading is enabled.
107 * Handle permission checking elsewhere in order to be able to show
108 * custom error messages.
109 *
110 * @param User $user
111 * @return bool
112 */
113 public function userCanExecute( $user ) {
114 return UploadBase::isEnabled() && parent::userCanExecute( $user );
115 }
116
117 /**
118 * Special page entry point
119 */
120 public function execute( $par ) {
121 global $wgUser, $wgOut, $wgRequest;
122
123 $this->setHeaders();
124 $this->outputHeader();
125
126 # Check uploading enabled
127 if( !UploadBase::isEnabled() ) {
128 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
129 return;
130 }
131
132 # Check permissions
133 global $wgGroupPermissions;
134 if( !$wgUser->isAllowed( 'upload' ) ) {
135 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
136 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
137 // Custom message if logged-in users without any special rights can upload
138 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
139 } else {
140 $wgOut->permissionRequired( 'upload' );
141 }
142 return;
143 }
144
145 # Check blocks
146 if( $wgUser->isBlocked() ) {
147 $wgOut->blockedPage();
148 return;
149 }
150
151 # Check whether we actually want to allow changing stuff
152 if( wfReadOnly() ) {
153 $wgOut->readOnlyPage();
154 return;
155 }
156
157 # Unsave the temporary file in case this was a cancelled upload
158 if ( $this->mCancelUpload ) {
159 if ( !$this->unsaveUploadedFile() )
160 # Something went wrong, so unsaveUploadedFile showed a warning
161 return;
162 }
163
164 # Process upload or show a form
165 if ( $this->mTokenOk && !$this->mCancelUpload
166 && ( $this->mUpload && $this->mUploadClicked ) ) {
167 $this->processUpload();
168 } else {
169 # Backwards compatibility hook
170 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
171 {
172 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
173 return;
174 }
175
176 $this->showUploadForm( $this->getUploadForm() );
177 }
178
179 # Cleanup
180 if ( $this->mUpload )
181 $this->mUpload->cleanupTempFile();
182 }
183
184 /**
185 * Show the main upload form
186 *
187 * @param mixed $form An HTMLForm instance or HTML string to show
188 */
189 protected function showUploadForm( $form ) {
190 # Add links if file was previously deleted
191 if ( !$this->mDesiredDestName ) {
192 $this->showViewDeletedLinks();
193 }
194
195 if ( $form instanceof HTMLForm ) {
196 $form->show();
197 } else {
198 global $wgOut;
199 $wgOut->addHTML( $form );
200 }
201
202 }
203
204 /**
205 * Get an UploadForm instance with title and text properly set.
206 *
207 * @param string $message HTML string to add to the form
208 * @param string $sessionKey Session key in case this is a stashed upload
209 * @return UploadForm
210 */
211 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
212 global $wgOut;
213
214 # Initialize form
215 $form = new UploadForm( array(
216 'watch' => $this->getWatchCheck(),
217 'forreupload' => $this->mForReUpload,
218 'sessionkey' => $sessionKey,
219 'hideignorewarning' => $hideIgnoreWarning,
220 'destwarningack' => (bool)$this->mDestWarningAck,
221
222 'texttop' => $this->uploadFormTextTop,
223 'textaftersummary' => $this->uploadFormTextAfterSummary,
224 ) );
225 $form->setTitle( $this->getTitle() );
226
227 # Check the token, but only if necessary
228 if( !$this->mTokenOk && !$this->mCancelUpload
229 && ( $this->mUpload && $this->mUploadClicked ) ) {
230 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
231 }
232
233 # Add text to form
234 $form->addPreText( '<div id="uploadtext">' . wfMsgExt( 'uploadtext', 'parse' ) . '</div>');
235 # Add upload error message
236 $form->addPreText( $message );
237
238 # Add footer to form
239 $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
240 if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) ) {
241 $form->addPostText( '<div id="mw-upload-footer-message">'
242 . $wgOut->parse( $uploadFooter ) . "</div>\n" );
243 }
244
245 return $form;
246
247 }
248
249 /**
250 * Shows the "view X deleted revivions link""
251 */
252 protected function showViewDeletedLinks() {
253 global $wgOut, $wgUser;
254
255 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
256 // Show a subtitle link to deleted revisions (to sysops et al only)
257 if( $title instanceof Title ) {
258 $count = $title->isDeleted();
259 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
260 $link = wfMsgExt(
261 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
262 array( 'parse', 'replaceafter' ),
263 $wgUser->getSkin()->linkKnown(
264 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
265 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
266 )
267 );
268 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
269 }
270 }
271
272 // Show the relevant lines from deletion log (for still deleted files only)
273 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
274 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
275 }
276 }
277
278 /**
279 * Stashes the upload and shows the main upload form.
280 *
281 * Note: only errors that can be handled by changing the name or
282 * description should be redirected here. It should be assumed that the
283 * file itself is sane and has passed UploadBase::verifyFile. This
284 * essentially means that UploadBase::VERIFICATION_ERROR and
285 * UploadBase::EMPTY_FILE should not be passed here.
286 *
287 * @param string $message HTML message to be passed to mainUploadForm
288 */
289 protected function showRecoverableUploadError( $message ) {
290 $sessionKey = $this->mUpload->stashSession();
291 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
292 '<div class="error">' . $message . "</div>\n";
293
294 $form = $this->getUploadForm( $message, $sessionKey );
295 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
296 $this->showUploadForm( $form );
297 }
298 /**
299 * Stashes the upload, shows the main form, but adds an "continue anyway button".
300 * Also checks whether there are actually warnings to display.
301 *
302 * @param array $warnings
303 * @return boolean true if warnings were displayed, false if there are no
304 * warnings and the should continue processing like there was no warning
305 */
306 protected function showUploadWarning( $warnings ) {
307 global $wgUser;
308
309 # If there are no warnings, or warnings we can ignore, return early
310 if ( !$warnings || ( count( $warnings ) == 1 &&
311 isset( $warnings['exists']) && $this->mDestWarningAck ) ) {
312 return false;
313 }
314
315 $sessionKey = $this->mUpload->stashSession();
316
317 $sk = $wgUser->getSkin();
318
319 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
320 . '<ul class="warning">';
321 foreach( $warnings as $warning => $args ) {
322 $msg = '';
323 if( $warning == 'exists' ) {
324 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
325 } elseif( $warning == 'duplicate' ) {
326 $msg = self::getDupeWarning( $args );
327 } elseif( $warning == 'duplicate-archive' ) {
328 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
329 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
330 . "</li>\n";
331 } else {
332 if ( $args === true )
333 $args = array();
334 elseif ( !is_array( $args ) )
335 $args = array( $args );
336 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
337 }
338 $warningHtml .= $msg;
339 }
340 $warningHtml .= "</ul>\n";
341 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
342
343 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
344 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
345 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
346 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
347
348 $this->showUploadForm( $form );
349
350 # Indicate that we showed a form
351 return true;
352 }
353
354 /**
355 * Show the upload form with error message, but do not stash the file.
356 *
357 * @param string $message
358 */
359 protected function showUploadError( $message ) {
360 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
361 '<div class="error">' . $message . "</div>\n";
362 $this->showUploadForm( $this->getUploadForm( $message ) );
363 }
364
365 /**
366 * Do the upload.
367 * Checks are made in SpecialUpload::execute()
368 */
369 protected function processUpload() {
370 global $wgUser, $wgOut;
371
372 // Verify permissions
373 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
374 if( $permErrors !== true ) {
375 $wgOut->showPermissionsErrorPage( $permErrors );
376 return;
377 }
378
379 // Fetch the file if required
380 $status = $this->mUpload->fetchFile();
381 if( !$status->isOK() ) {
382 $this->showUploadForm( $this->getUploadForm( $wgOut->parse( $status->getWikiText() ) ) );
383 return;
384 }
385
386 // Deprecated backwards compatibility hook
387 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
388 {
389 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
390 return array( 'status' => UploadBase::BEFORE_PROCESSING );
391 }
392
393
394 // Upload verification
395 $details = $this->mUpload->verifyUpload();
396 if ( $details['status'] != UploadBase::OK ) {
397 $this->processVerificationError( $details );
398 return;
399 }
400
401 $this->mLocalFile = $this->mUpload->getLocalFile();
402
403 // Check warnings if necessary
404 if( !$this->mIgnoreWarning ) {
405 $warnings = $this->mUpload->checkWarnings();
406 if( $this->showUploadWarning( $warnings ) ) {
407 return;
408 }
409 }
410
411 // Get the page text if this is not a reupload
412 if( !$this->mForReUpload ) {
413 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
414 $this->mCopyrightStatus, $this->mCopyrightSource );
415 } else {
416 $pageText = false;
417 }
418 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
419 if ( !$status->isGood() ) {
420 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
421 return;
422 }
423
424 // Success, redirect to description page
425 $this->mUploadSuccessful = true;
426 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
427 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
428
429 }
430
431 /**
432 * Get the initial image page text based on a comment and optional file status information
433 */
434 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
435 global $wgUseCopyrightUpload;
436 if ( $wgUseCopyrightUpload ) {
437 $licensetxt = '';
438 if ( $license != '' ) {
439 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
440 }
441 $pageText = '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n" .
442 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
443 "$licensetxt" .
444 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
445 } else {
446 if ( $license != '' ) {
447 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n";
448 $pageText = $filedesc .
449 '== ' . wfMsgForContent ( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
450 } else {
451 $pageText = $comment;
452 }
453 }
454 return $pageText;
455 }
456
457 /**
458 * See if we should check the 'watch this page' checkbox on the form
459 * based on the user's preferences and whether we're being asked
460 * to create a new file or update an existing one.
461 *
462 * In the case where 'watch edits' is off but 'watch creations' is on,
463 * we'll leave the box unchecked.
464 *
465 * Note that the page target can be changed *on the form*, so our check
466 * state can get out of sync.
467 */
468 protected function getWatchCheck() {
469 global $wgUser;
470 if( $wgUser->getOption( 'watchdefault' ) ) {
471 // Watch all edits!
472 return true;
473 }
474
475 $local = wfLocalFile( $this->mDesiredDestName );
476 if( $local && $local->exists() ) {
477 // We're uploading a new version of an existing file.
478 // No creation, so don't watch it if we're not already.
479 return $local->getTitle()->userIsWatching();
480 } else {
481 // New page should get watched if that's our option.
482 return $wgUser->getOption( 'watchcreations' );
483 }
484 }
485
486
487 /**
488 * Provides output to the user for a result of UploadBase::verifyUpload
489 *
490 * @param array $details Result of UploadBase::verifyUpload
491 */
492 protected function processVerificationError( $details ) {
493 global $wgFileExtensions, $wgLang;
494
495 switch( $details['status'] ) {
496
497 /** Statuses that only require name changing **/
498 case UploadBase::MIN_LENGTH_PARTNAME:
499 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
500 break;
501 case UploadBase::ILLEGAL_FILENAME:
502 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
503 'parseinline', $details['filtered'] ) );
504 break;
505 case UploadBase::OVERWRITE_EXISTING_FILE:
506 $this->showRecoverableUploadError( wfMsgExt( $details['overwrite'],
507 'parseinline' ) );
508 break;
509 case UploadBase::FILETYPE_MISSING:
510 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
511 'parseinline' ) );
512 break;
513
514 /** Statuses that require reuploading **/
515 case UploadBase::EMPTY_FILE:
516 $this->showUploadForm( $this->getUploadForm( wfMsgHtml( 'emptyfile' ) ) );
517 break;
518 case UploadBase::FILETYPE_BADTYPE:
519 $finalExt = $details['finalExt'];
520 $this->showUploadError(
521 wfMsgExt( 'filetype-banned-type',
522 array( 'parseinline' ),
523 htmlspecialchars( $finalExt ),
524 implode(
525 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
526 $wgFileExtensions
527 ),
528 $wgLang->formatNum( count( $wgFileExtensions ) )
529 )
530 );
531 break;
532 case UploadBase::VERIFICATION_ERROR:
533 unset( $details['status'] );
534 $code = array_shift( $details['details'] );
535 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
536 break;
537 case UploadBase::HOOK_ABORTED:
538 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
539 $args = $details['error'];
540 $error = array_shift( $args );
541 } else {
542 $error = $details['error'];
543 $args = null;
544 }
545
546 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
547 break;
548 default:
549 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
550 }
551 }
552
553 /**
554 * Remove a temporarily kept file stashed by saveTempUploadedFile().
555 * @access private
556 * @return success
557 */
558 protected function unsaveUploadedFile() {
559 global $wgOut;
560 if ( !( $this->mUpload instanceof UploadFromStash ) )
561 return true;
562 $success = $this->mUpload->unsaveUploadedFile();
563 if ( ! $success ) {
564 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
565 return false;
566 } else {
567 return true;
568 }
569 }
570
571 /*** Functions for formatting warnings ***/
572
573 /**
574 * Formats a result of UploadBase::getExistsWarning as HTML
575 * This check is static and can be done pre-upload via AJAX
576 *
577 * @param array $exists The result of UploadBase::getExistsWarning
578 * @return string Empty string if there is no warning or an HTML fragment
579 */
580 public static function getExistsWarning( $exists ) {
581 global $wgUser, $wgContLang;
582
583 if ( !$exists )
584 return '';
585
586 $file = $exists['file'];
587 $filename = $file->getTitle()->getPrefixedText();
588 $warning = '';
589
590 $sk = $wgUser->getSkin();
591
592 if( $exists['warning'] == 'exists' ) {
593 // Exact match
594 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
595 } elseif( $exists['warning'] == 'page-exists' ) {
596 // Page exists but file does not
597 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
598 } elseif ( $exists['warning'] == 'exists-normalized' ) {
599 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
600 $exists['normalizedFile']->getTitle()->getPrefixedText() );
601 } elseif ( $exists['warning'] == 'thumb' ) {
602 // Swapped argument order compared with other messages for backwards compatibility
603 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
604 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
605 } elseif ( $exists['warning'] == 'thumb-name' ) {
606 // Image w/o '180px-' does not exists, but we do not like these filenames
607 $name = $file->getName();
608 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
609 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
610 } elseif ( $exists['warning'] == 'bad-prefix' ) {
611 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
612 } elseif ( $exists['warning'] == 'was-deleted' ) {
613 # If the file existed before and was deleted, warn the user of this
614 $ltitle = SpecialPage::getTitleFor( 'Log' );
615 $llink = $sk->linkKnown(
616 $ltitle,
617 wfMsgHtml( 'deletionlog' ),
618 array(),
619 array(
620 'type' => 'delete',
621 'page' => $filename
622 )
623 );
624 $warning = wfMsgWikiHtml( 'filewasdeleted', $llink );
625 }
626
627 return $warning;
628 }
629
630 /**
631 * Get a list of warnings
632 *
633 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
634 * @return array list of warning messages
635 */
636 public static function ajaxGetExistsWarning( $filename ) {
637 $file = wfFindFile( $filename );
638 if( !$file ) {
639 // Force local file so we have an object to do further checks against
640 // if there isn't an exact match...
641 $file = wfLocalFile( $filename );
642 }
643 $s = '&nbsp;';
644 if ( $file ) {
645 $exists = UploadBase::getExistsWarning( $file );
646 $warning = self::getExistsWarning( $exists );
647 if ( $warning !== '' ) {
648 $s = "<div>$warning</div>";
649 }
650 }
651 return $s;
652 }
653
654 /**
655 * Construct a warning and a gallery from an array of duplicate files.
656 */
657 public static function getDupeWarning( $dupes ) {
658 if( $dupes ) {
659 global $wgOut;
660 $msg = "<gallery>";
661 foreach( $dupes as $file ) {
662 $title = $file->getTitle();
663 $msg .= $title->getPrefixedText() .
664 "|" . $title->getText() . "\n";
665 }
666 $msg .= "</gallery>";
667 return "<li>" .
668 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
669 $wgOut->parse( $msg ) .
670 "</li>\n";
671 } else {
672 return '';
673 }
674 }
675
676 }
677
678 /**
679 * Sub class of HTMLForm that provides the form section of SpecialUpload
680 */
681 class UploadForm extends HTMLForm {
682 protected $mWatch;
683 protected $mForReUpload;
684 protected $mSessionKey;
685 protected $mHideIgnoreWarning;
686 protected $mDestWarningAck;
687
688 protected $mTextTop;
689 protected $mTextAfterSummary;
690
691 protected $mSourceIds;
692
693 public function __construct( $options = array() ) {
694 global $wgLang;
695
696 $this->mWatch = !empty( $options['watch'] );
697 $this->mForReUpload = !empty( $options['forreupload'] );
698 $this->mSessionKey = isset( $options['sessionkey'] )
699 ? $options['sessionkey'] : '';
700 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
701 $this->mDestWarningAck = !empty( $options['destwarningack'] );
702
703 $this->mTextTop = $options['texttop'];
704 $this->mTextAfterSummary = $options['textaftersummary'];
705
706 $sourceDescriptor = $this->getSourceSection();
707 $descriptor = $sourceDescriptor
708 + $this->getDescriptionSection()
709 + $this->getOptionsSection();
710
711 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
712 parent::__construct( $descriptor, 'upload' );
713
714 # Set some form properties
715 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
716 $this->setSubmitName( 'wpUpload' );
717 $this->setSubmitTooltip( 'upload' );
718 $this->setId( 'mw-upload-form' );
719
720 # Build a list of IDs for javascript insertion
721 $this->mSourceIds = array();
722 foreach ( $sourceDescriptor as $key => $field ) {
723 if ( !empty( $field['id'] ) )
724 $this->mSourceIds[] = $field['id'];
725 }
726
727 }
728
729 /**
730 * Get the descriptor of the fieldset that contains the file source
731 * selection. The section is 'source'
732 *
733 * @return array Descriptor array
734 */
735 protected function getSourceSection() {
736 global $wgLang, $wgUser, $wgRequest;
737
738 if ( $this->mSessionKey ) {
739 return array(
740 'wpSessionKey' => array(
741 'type' => 'hidden',
742 'default' => $this->mSessionKey,
743 ),
744 'wpSourceType' => array(
745 'type' => 'hidden',
746 'default' => 'Stash',
747 ),
748 );
749 }
750
751 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
752 $radio = $canUploadByUrl;
753 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
754
755 $descriptor = array();
756 if ( $this->mTextTop ) {
757 $descriptor['UploadFormTextTop'] = array(
758 'type' => 'info',
759 'section' => 'source',
760 'default' => $this->mTextTop,
761 'raw' => true,
762 );
763 }
764
765 $descriptor['UploadFile'] = array(
766 'class' => 'UploadSourceField',
767 'section' => 'source',
768 'type' => 'file',
769 'id' => 'wpUploadFile',
770 'label-message' => 'sourcefilename',
771 'upload-type' => 'File',
772 'radio' => &$radio,
773 'help' => wfMsgExt( 'upload-maxfilesize',
774 array( 'parseinline', 'escapenoentities' ),
775 $wgLang->formatSize(
776 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) )
777 )
778 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
779 'checked' => $selectedSourceType == 'file',
780 );
781 if ( $canUploadByUrl ) {
782 global $wgMaxUploadSize;
783 $descriptor['UploadFileURL'] = array(
784 'class' => 'UploadSourceField',
785 'section' => 'source',
786 'id' => 'wpUploadFileURL',
787 'label-message' => 'sourceurl',
788 'upload-type' => 'url',
789 'radio' => &$radio,
790 'help' => wfMsgExt( 'upload-maxfilesize',
791 array( 'parseinline', 'escapenoentities' ),
792 $wgLang->formatSize( $wgMaxUploadSize )
793 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
794 'checked' => $selectedSourceType == 'url',
795 );
796 }
797 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
798
799 $descriptor['Extensions'] = array(
800 'type' => 'info',
801 'section' => 'source',
802 'default' => $this->getExtensionsMessage(),
803 'raw' => true,
804 );
805 return $descriptor;
806 }
807
808
809 /**
810 * Get the messages indicating which extensions are preferred and prohibitted.
811 *
812 * @return string HTML string containing the message
813 */
814 protected function getExtensionsMessage() {
815 # Print a list of allowed file extensions, if so configured. We ignore
816 # MIME type here, it's incomprehensible to most people and too long.
817 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
818 $wgFileExtensions, $wgFileBlacklist;
819
820 $allowedExtensions = '';
821 if( $wgCheckFileExtensions ) {
822 if( $wgStrictFileExtensions ) {
823 # Everything not permitted is banned
824 $extensionsList =
825 '<div id="mw-upload-permitted">' .
826 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
827 "</div>\n";
828 } else {
829 # We have to list both preferred and prohibited
830 $extensionsList =
831 '<div id="mw-upload-preferred">' .
832 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
833 "</div>\n" .
834 '<div id="mw-upload-prohibited">' .
835 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
836 "</div>\n";
837 }
838 } else {
839 # Everything is permitted.
840 $extensionsList = '';
841 }
842 return $extensionsList;
843 }
844
845 /**
846 * Get the descriptor of the fieldset that contains the file description
847 * input. The section is 'description'
848 *
849 * @return array Descriptor array
850 */
851 protected function getDescriptionSection() {
852 global $wgUser, $wgOut;
853
854 $cols = intval( $wgUser->getOption( 'cols' ) );
855 if( $wgUser->getOption( 'editwidth' ) ) {
856 $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
857 }
858
859 $descriptor = array(
860 'DestFile' => array(
861 'type' => 'text',
862 'section' => 'description',
863 'id' => 'wpDestFile',
864 'label-message' => 'destfilename',
865 'size' => 60,
866 ),
867 'UploadDescription' => array(
868 'type' => 'textarea',
869 'section' => 'description',
870 'id' => 'wpUploadDescription',
871 'label-message' => $this->mForReUpload
872 ? 'filereuploadsummary'
873 : 'fileuploadsummary',
874 'cols' => $cols,
875 'rows' => 8,
876 )
877 );
878 if ( $this->mTextAfterSummary ) {
879 $descriptor['UploadFormTextAfterSummary'] = array(
880 'type' => 'info',
881 'section' => 'description',
882 'default' => $this->mTextAfterSummary,
883 'raw' => true,
884 );
885 }
886
887 $descriptor += array(
888 'EditTools' => array(
889 'type' => 'edittools',
890 'section' => 'description',
891 ),
892 'License' => array(
893 'type' => 'select',
894 'class' => 'Licenses',
895 'section' => 'description',
896 'id' => 'wpLicense',
897 'label-message' => 'license',
898 ),
899 );
900 if ( $this->mForReUpload )
901 $descriptor['DestFile']['readonly'] = true;
902
903 global $wgUseCopyrightUpload;
904 if ( $wgUseCopyrightUpload ) {
905 $descriptor['UploadCopyStatus'] = array(
906 'type' => 'text',
907 'section' => 'description',
908 'id' => 'wpUploadCopyStatus',
909 'label-message' => 'filestatus',
910 );
911 $descriptor['UploadSource'] = array(
912 'type' => 'text',
913 'section' => 'description',
914 'id' => 'wpUploadSource',
915 'label-message' => 'filesource',
916 );
917 }
918
919 return $descriptor;
920 }
921
922 /**
923 * Get the descriptor of the fieldset that contains the upload options,
924 * such as "watch this file". The section is 'options'
925 *
926 * @return array Descriptor array
927 */
928 protected function getOptionsSection() {
929 global $wgUser, $wgOut;
930
931 if( $wgUser->isLoggedIn() ) {
932 $descriptor = array(
933 'Watchthis' => array(
934 'type' => 'check',
935 'id' => 'wpWatchthis',
936 'label-message' => 'watchthisupload',
937 'section' => 'options',
938 )
939 );
940 }
941 if( !$this->mHideIgnoreWarning ) {
942 $descriptor['IgnoreWarning'] = array(
943 'type' => 'check',
944 'id' => 'wpIgnoreWarning',
945 'label-message' => 'ignorewarnings',
946 'section' => 'options',
947 );
948 }
949
950 $descriptor['wpDestFileWarningAck'] = array(
951 'type' => 'hidden',
952 'id' => 'wpDestFileWarningAck',
953 'default' => $this->mDestWarningAck ? '1' : '',
954 );
955
956 return $descriptor;
957
958 }
959
960 /**
961 * Add the upload JS and show the form.
962 */
963 public function show() {
964 $this->addUploadJS();
965 parent::show();
966 }
967
968 /**
969 * Add upload JS to $wgOut
970 *
971 * @param bool $autofill Whether or not to autofill the destination
972 * filename text box
973 */
974 protected function addUploadJS( ) {
975 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI;
976 global $wgOut;
977
978 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
979 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
980
981 $scriptVars = array(
982 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
983 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
984 'wgUploadAutoFill' => !$this->mForReUpload,
985 'wgUploadSourceIds' => $this->mSourceIds,
986 );
987
988 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
989
990 // For <charinsert> support
991 $wgOut->addScriptFile( 'edit.js' );
992 $wgOut->addScriptFile( 'upload.js' );
993 }
994
995 /**
996 * Empty function; submission is handled elsewhere.
997 *
998 * @return bool false
999 */
1000 function trySubmit() {
1001 return false;
1002 }
1003
1004 }
1005
1006 /**
1007 * A form field that contains a radio box in the label
1008 */
1009 class UploadSourceField extends HTMLTextField {
1010 function getLabelHtml() {
1011 $id = "wpSourceType{$this->mParams['upload-type']}";
1012 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1013
1014 if ( !empty( $this->mParams['radio'] ) ) {
1015 $attribs = array(
1016 'name' => 'wpSourceType',
1017 'type' => 'radio',
1018 'id' => $id,
1019 'value' => $this->mParams['upload-type'],
1020 );
1021 if ( !empty( $this->mParams['checked'] ) )
1022 $attribs['checked'] = 'checked';
1023 $label .= Html::element( 'input', $attribs );
1024 }
1025
1026 return Html::rawElement( 'td', array( 'class' => 'mw-label' ), $label );
1027 }
1028 function getSize() {
1029 return isset( $this->mParams['size'] )
1030 ? $this->mParams['size']
1031 : 60;
1032 }
1033 }
1034